/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.javlov.example.grid;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.util.Arrays;

import net.javlov.example.WorldView;


public class GridWorldView extends WorldView {
	
	private static final long serialVersionUID = -193232841584505904L;
	
	protected SimpleGridWorld model;
	
	protected int cellDim;
	
	public GridWorldView(SimpleGridWorld w, int cellDim) {
		this.cellDim = cellDim;
		setModel(w);
	}
	
	public SimpleGridWorld getModel() {
		return model;
	}

	public void setModel(SimpleGridWorld model) {
		this.model = model;
		modelWidth = model.getWidth();
		modelHeight = model.getHeight();
		setPreferredSize(new Dimension((int)(modelWidth*cellDim), (int)(modelHeight*cellDim)));
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D) g;
		saveXform = g2d.getTransform();
		g2d.transform(scaleXform);
		
		//draw background
		g2d.setColor(Color.white);
		g2d.fillRect(0, 0, modelWidth*cellDim, modelHeight*cellDim);
		
		//draw grid
		for(int h = 0; h < modelHeight; h++)
    		for(int w = 0; w < modelWidth; w++) {
    			g2d.setColor(Color.yellow);
    			g2d.drawRect(w*cellDim, h*cellDim, cellDim, cellDim);
    			g2d.setColor(Color.black);
    			//g2d.drawString(""+cells[w][h].getOccupiers().size(), (int)cells[w][h].x + 5, (int)cells[w][h].y + 15);
    		}
		g2d.setColor(Color.black);

		//draw agent
		double[] pos = model.getCurrentState().getData();
		if ( pos != null ) {
			g2d.drawOval((int)((pos[0] + 0.05)*cellDim), (int)((pos[1] + 0.05)*cellDim),
						(int)(cellDim*0.9), (int)(cellDim*0.9));
		}
		
		//draw goal
		pos = model.getGoalState().getData();
		if ( pos != null ) {			
			g2d.drawLine((int)((pos[0]+0.05)*cellDim), (int)((pos[1]+0.05)*cellDim),
						(int)((pos[0]+0.95)*cellDim), (int)((pos[1]+0.95)*cellDim));
			g2d.drawLine((int)((pos[0]+0.05)*cellDim), (int)((pos[1] + 0.95)*cellDim),
					(int)((pos[0] + 0.95)*cellDim), (int)((pos[1] + 0.05)*cellDim));
		}
		
		drawOthers(g2d);
		
		//return to original transform
		g2d.setTransform(saveXform);
	}
}